//
//  AEAppDelegateTool.m
//  AESOLAR_IOS
//
//  Created by Bin Tang on 2024/10/13.
//  Copyright © 2024 Mr.Wang. All rights reserved.
//

#import "AEAppDelegateTool.h"
#import "TYZNetworkConfig.h"
//#import "AEUserInfoRequest.h" // 获取用户信息
#import "AE_Solar-Swift.h"
#import "TYZNavRootVCInfo.h"
#import "AEHomePageViewController.h"
#import "AEAccountShareRequest.h"
#import "AESysConfigRequest.h"

@interface AEAppDelegateTool () <UITabBarControllerDelegate>

@end

@implementation AEAppDelegateTool

+ (instancetype)sharedInstance {
    static AEAppDelegateTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    [self setupUUID];
    
    [TYZNetworkConfig sharedConfig].baseUrl = kBaseUrl;
    
    // 用户信息
    id userInfo = [TYZKeychain load:kUserInfo];
    if (userInfo) {
        self.userInfoModel = userInfo;
    }
    
    [self setupWXApi];
    
    
    [self setSvProgressHUD];
    
    [self requestWithUserInfo:^(EDSRespondDataEntity * _Nonnull respond) {
        
    }];
}

/// 微信初始化
- (void)setupWXApi
{
    if (![WXApi isWXAppInstalled])
    {
        return;
    }
    BOOL ret = [WXApi registerApp:kWEIXIN_APP_ID universalLink:kWEIXIN_APP_UNIVERSAL_LINK];
    if (ret)
    {
        debugLog(@"微信sdk初始化成功");
    }
    
    /*
     WXULCheckStepParams,
     WXULCheckStepSystemVersion,
     WXULCheckStepWechatVersion,
     WXULCheckStepSDKInnerOperation,
     WXULCheckStepLaunchWechat,
     WXULCheckStepBackToCurrentApp, --- 5
     WXULCheckStepFinal,
     */
//    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult * _Nonnull result) {
//
//        NSString *log = [NSString stringWithFormat:@"微信测试函数：%@, state=%u, errorInfo=%@, 修正建议=%@", @(step), result.success, result.errorInfo, result.suggestion];
//        debugLog(@"%@", log);
////        [[TYZLogManager sharedInstance] logInfo:@"" logStr:log, nil];
//    }];
}


/**
 唯一标识码
 */
- (NSString *)setupUUID
{
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *uuid = [TYZKeychain load:bundleId];
    if ([objectNull(uuid) isEqualToString:@""])
    {
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:bundleId data:uuid];
    }
    return uuid;
}

- (NSString *)deviceId
{
    return [self setupUUID];
}

- (void)setSvProgressHUD
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD setMinimumDismissTimeInterval:1.5];
}

/// 保存用户信息
/// - Parameter userInfo: userInfo description
- (void)saveUserInfo:(AEUserInfoModel *)userInfo {
    self.userInfoModel = userInfo;
    [TYZKeychain save:kUserInfo data:userInfo];
}

/// 获取用户信息
- (AEUserInfoModel *)getUserInfo {
    return self.userInfoModel;
}

- (NSString *)getUUID {
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *uuid = [TYZKeychain load:bundleId];
    if (!uuid) {
        uuid = [NSString stringWithUUID];
        [TYZKeychain save:bundleId data:objectNull(uuid)];
    }
    return uuid;
}

/// 删除用户信息
- (void)removeUserInfo {
    [TYZKeychain remove:kUserInfo];
    self.userInfoModel = nil;
}

/// 获取用户信息
/// - Parameter completion: completion description
- (void)requestWithUserInfo:(RequestCompletionBlock)completion {
    
}

/// 到主视图
- (TYZCustomTabBarController *)getMainTabBarVC {
    // 首页
    NSString *title = [AEStringExten localizedValueWithKey:@"首页"];
    
    TYZPageConfigration *config = [AEHomePageViewController setupConfig];
    
    NSArray *titles = [AEHomePageViewController setupMenuTitles];
    NSArray *subVcs = [AEHomePageViewController setupViewControllers:@{}];
    AEHomePageViewController *rootVC = [[AEHomePageViewController alloc] initPageWithControllers:subVcs titles:titles config:config];

    TYZNavRootVCInfo *mainInfo = [[TYZNavRootVCInfo alloc] initWithInfo:title clsName:nil imgNorName:@"ic_tab_main_nor" imgSelName:@"ic_tab_main_sel"];
    mainInfo.vc = rootVC;//[[HomePageViewController alloc] init];
    
    // 检验
    title = [AEStringExten localizedValueWithKey:@"检验"];
    TYZNavRootVCInfo *checkInfo = [[TYZNavRootVCInfo alloc] initWithInfo:title clsName:nil imgNorName:@"ic_tab_check_nor" imgSelName:@"ic_tab_check_sel"];
    checkInfo.vc = [[CheckViewController alloc] init];
    
    // 积分
    title = [AEStringExten localizedValueWithKey:@"积分"];
    TYZNavRootVCInfo *pointsInfo = [[TYZNavRootVCInfo alloc] initWithInfo:title clsName:nil imgNorName:@"ic_tab_points_nor" imgSelName:@"ic_tab_points_sel"];
    pointsInfo.vc = [[AEPointsMallViewController alloc] init];
    
    // 反馈
    title = [AEStringExten localizedValueWithKey:@"反馈"];
    TYZNavRootVCInfo *feedbackInfo = [[TYZNavRootVCInfo alloc] initWithInfo:title clsName:nil imgNorName:@"tab_feedback_nor" imgSelName:@"tab_feedback_sel"];
    feedbackInfo.vc = [[ServiceViewController alloc] init];
    
    // 我的
    title = [AEStringExten localizedValueWithKey:@"我的"];
    TYZNavRootVCInfo *mineInfo = [[TYZNavRootVCInfo alloc] initWithInfo:title clsName:nil imgNorName:@"ic_tab_mine_nor" imgSelName:@"ic_tab_mine_sel"];
    mineInfo.vc = [[AEPersonViewController alloc] init];
    
    TYZCustomTabBarController *rootTabBar = [[TYZCustomTabBarController alloc] initWithShowMiddleBtn:NO midNorImgName:nil midSelImgName:nil];
    rootTabBar.delegate = self;
//    NSArray *vcs = @[mainInfo, checkInfo, pointsInfo, mineInfo];
    NSArray *vcs = @[mainInfo, checkInfo, feedbackInfo, mineInfo];
    
    TYZNavInfo *navInfo = [[TYZNavInfo alloc] initWithNavBackgroundColor:kNavBarBackgroundColor titleFont:kNavBarTitleFont titleColor:kNavBarTitleColor];
    
    [rootTabBar setupChildViewController:vcs navInfo:navInfo];
    [rootTabBar setupTabBarItemTextAttributes:kTabBarItemTitleNorColor selTitleColor:kTabBarItemTitleSelColor titleFont:kTabBarItemTitleFont];
//    kThemeColor
    self.rootTabBar = rootTabBar;
    return rootTabBar;
}

- (void)setSelectedTabBarIndex:(NSInteger)selectedTabBarIndex {
    if (self.rootTabBar) {
        self.rootTabBar.selectedIndex = selectedTabBarIndex;
    }
}

/// 得到配置信息
/// - Parameter completion: completion description
- (void)requestWithSysConfig:(RequestCompletionBlock)completion {
    @weakify(self);
    AESysConfigRequest *request = [[AESysConfigRequest alloc] init];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            self.configModel = respond.data;
        }
        if (completion) {
            completion(request.responseModelObject);
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        if (completion) {
            completion(request.responseModelObject);
        }
    }];
}

/// 显示分享弹窗
- (void)showShareVC:(UIViewController *)vc {
    
    
    NSURL *url = [NSURL URLWithString:self.configModel.apple_store];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[url] applicationActivities:nil];
    @weakify(self);
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        @strongify(self);
        if (completed) {
//            debugLog(@"完成");
            [self requestWithShareSuccess];
        } else {
//            debugLog(@"未完成");
        }
    };
    
    [vc presentViewController:activityVC animated:YES completion:^{
//        debugLog(@"完成了");
    }];
}


/// 分享成功后调用
- (void)requestWithShareSuccess {
//    @weakify(self);
    [self requestWithShareSuccess:^(EDSRespondDataEntity * _Nonnull respond) {
//        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            // 发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoRefresh" object:nil];
        } else {
            [SVProgressHUD showInfoWithStatus:respond.msg];
        }
    }];
}

/// 分享成功后调用的接口
/// - Parameter completion: completion description
- (void)requestWithShareSuccess:(RequestCompletionBlock)completion {
    @weakify(self);
    NSString *userId = [AEUserCommonInfo getUserId];
    AEAccountShareRequest *request = [[AEAccountShareRequest alloc] initWithUserId:userId];
    [request startWithCompletionBlockWithSuccess:^(__kindof TYZBaseRequest * _Nonnull request) {
//        @strongify(self);
        EDSRespondDataEntity *respond = request.responseModelObject;
        if (respond.code == EDS_NETWORK_SUCCESS) {
            
        }
        if (completion) {
            completion(request.responseModelObject);
        }
    } failure:^(__kindof TYZBaseRequest * _Nonnull request) {
        if (completion) {
            completion(request.responseModelObject);
        }
    }];
}




@end
